/**
 * 
 */
package com.hk.Mgr.web.controller.product;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.order.OverseaSafeInfoReq;
import com.hk.Mgr.web.message.order.OverseaSafeInfoRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.entity.product.OverseaSafeInfo;
import com.hk.commons.utils.sys.DateHelper;
import com.hk.service.product.IOverseaSafeInfo;
import com.hk.yingmi.FundSearchCtrl;

/**
 * @author psx 海外保险产品实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/OverseaSafeInfoCtrl")
public class OverseaSafeInfoCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(OverseaSafeInfoCtrl.class);
	
	@Autowired
	private IOverseaSafeInfo overseaSafeInfoService;
	
	@Value("${photo_dir}")
	private String photoDir;
	
	@RequestMapping(value = "/uploadPic")
	public void uploadPic(MultipartHttpServletRequest request,
			HttpServletResponse response) {
		ResponseBase<OverseaSafeInfo> resp = new ResponseBase<OverseaSafeInfo>();
		try {

			MultipartFile mpf = request.getFile("Filedata");
			String id = request.getParameter("id"); // 商品id
			logger.info("id=" + id);
			logger.info("mpf:"+mpf);
			
			if (!mpf.isEmpty()) {
				long fileSize = mpf.getSize();
				
				// 文件大小大于3M
				if (fileSize > 3048576) {
					logger.error("error:file is so big!3M");
				} else {
					String fileType = mpf.getOriginalFilename().substring(
							mpf.getOriginalFilename().indexOf("."));
					String picName = DateHelper.getTimeStamp();
					String fileName = picName  + fileType; // 保存文件名称
					
					String savePath=photoDir;
					File ioFile = new File(savePath);
					if (!ioFile.exists()) {
						Boolean result = ioFile.mkdirs();
						logger.info("mkdirs result =" + result);
						if(!result){
							return;
						}
					}


					String filePath = savePath + File.separator + fileName;
					logger.info("filePath=" + filePath);
					
					mpf.transferTo(new File(filePath));
					OverseaSafeInfo model = new OverseaSafeInfo();
					if(id==null){
						model.setProPic(fileName);
						model.setCreateDate(new Timestamp(this.getCurrentTime()));
						Long rid=overseaSafeInfoService.add(model);
						model.setId(rid);
					}else{
						 model = overseaSafeInfoService.findById(Long.parseLong(id));
						 model.setProPic(fileName);
						overseaSafeInfoService.update(model);
					}
					resp.setResultCode(StatusCode.SUCCESS.key());
					resp.setResult(model);
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		PrintWriter printWrite =null;
		try {
			printWrite = response.getWriter();
			JSONObject json = JSONObject.fromObject(resp);
			printWrite.write(json.toString());
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
		} finally {
			if (null != printWrite)
				printWrite.close();
		}
	}
	
	
	/**
	 * @Title: getOverseaSafeInfoById
	 * @Description: 根据id获取系统模块信息
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getOverseaSafeInfoById", method = RequestMethod.POST)
	public ResponseBase<OverseaSafeInfoRes> getOverseaSafeInfoById(
			@RequestBody OverseaSafeInfoReq req) {
		ResponseBase<OverseaSafeInfoRes> resp = new ResponseBase<OverseaSafeInfoRes>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			OverseaSafeInfo overseaSafeInfo = overseaSafeInfoService.findById(req.getId());

			OverseaSafeInfoRes singleResp = new OverseaSafeInfoRes();
			ReqToModelHelper.copyReqValueToModel(overseaSafeInfo, singleResp);

			String proFeatureTxt, proEnsureTxt, coverCaseTxt, coverFlowTxt = "";
			if (overseaSafeInfo.getProFeature() != null) {
				proFeatureTxt = new String(overseaSafeInfo.getProFeature(), "UTF-8");
				singleResp.setProFeatureTxt(proFeatureTxt);
			}
			if (overseaSafeInfo.getProEnsure() != null) {
				proEnsureTxt = new String(overseaSafeInfo.getProEnsure(), "UTF-8");
				singleResp.setProEnsureTxt(proEnsureTxt);
			}
			if (overseaSafeInfo.getCoverCase() != null) {
				coverCaseTxt = new String(overseaSafeInfo.getCoverCase(), "UTF-8");
				singleResp.setCoverCaseTxt(coverCaseTxt);
			}
			if (overseaSafeInfo.getCoverFlow() != null) {
				coverFlowTxt = new String(overseaSafeInfo.getCoverFlow(), "UTF-8");
				singleResp.setCoverFlowTxt(coverFlowTxt);
			}

			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(singleResp);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getOverseaSafeInfoList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getOverseaSafeInfoList", method = RequestMethod.POST)
	public ResponseBase<List<OverseaSafeInfoRes>> getOverseaSafeInfoList(
			@RequestBody OverseaSafeInfoReq req) {
		ResponseBase<List<OverseaSafeInfoRes>> resp = new ResponseBase<List<OverseaSafeInfoRes>>();
		HqlFilter hqlFilter = new HqlFilter();
				
		// 产品类型
		if (req.getProdType() != null) {
			hqlFilter.addEQFilter("prodType", req.getProdType());
		}
		// 保险公司
		if (req.getSafeCompany() != null) {
			hqlFilter.addEQFilter("safeCompany", req.getSafeCompany());
		}
		// 名称
				if (StringUtils.isNotBlank(req.getName())) {
					hqlFilter.addEQFilter("name", req.getName());
				}
				
		hqlFilter.addSort("id");
		hqlFilter.addOrder("desc");
		
		logger.info("hqlFilter = " + hqlFilter.getWhereHql());
		try {
			List<OverseaSafeInfo> overseaSafeInfoList = overseaSafeInfoService
					.findByFilter(hqlFilter, req.getCurPage(),
							req.getPageSize());

			List<OverseaSafeInfoRes> respList = new ArrayList<OverseaSafeInfoRes>();
			// 根据模块id查询资源
			if (overseaSafeInfoList != null && !overseaSafeInfoList.isEmpty()) {
				OverseaSafeInfoRes singleResp = null;
				for (OverseaSafeInfo overseaSafeInfo : overseaSafeInfoList) {
					singleResp = new OverseaSafeInfoRes();

					ReqToModelHelper.copyReqValueToModel(overseaSafeInfo,
							singleResp);

					String proFeatureTxt, proEnsureTxt, coverCaseTxt, coverFlowTxt = "";
					if (overseaSafeInfo.getProFeature() != null) {
						proFeatureTxt = new String(overseaSafeInfo.getProFeature(), "UTF-8");
						singleResp.setProFeatureTxt(proFeatureTxt);
					}
					if (overseaSafeInfo.getProEnsure() != null) {
						proEnsureTxt = new String(overseaSafeInfo.getProEnsure(), "UTF-8");
						singleResp.setProEnsureTxt(proEnsureTxt);
					}
					if (overseaSafeInfo.getCoverCase() != null) {
						coverCaseTxt = new String(overseaSafeInfo.getCoverCase(), "UTF-8");
						singleResp.setCoverCaseTxt(coverCaseTxt);
					}
					if (overseaSafeInfo.getCoverFlow() != null) {
						coverFlowTxt = new String(overseaSafeInfo.getCoverFlow(), "UTF-8");
						singleResp.setCoverFlowTxt(coverFlowTxt);
					}

					respList.add(singleResp);
				}
			}
			Long total = overseaSafeInfoService.countByFilter(hqlFilter);
			resp.setSize(total);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(respList);

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: saveOverseaSafeInfo
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/saveOverseaSafeInfo", method = RequestMethod.POST)
	public ResponseBase<OverseaSafeInfo> saveOverseaSafeInfo(
			@RequestBody OverseaSafeInfoReq req) {
		ResponseBase<OverseaSafeInfo> resp = new ResponseBase<OverseaSafeInfo>();
		try {
			OverseaSafeInfo model = new OverseaSafeInfo();
			ReqToModelHelper.copyReqValueToModel(req, model);
			
			if (StringUtils.isNotBlank(req.getProFeatureTxt())) {
				byte[] proFeature = req.getProFeatureTxt().getBytes("UTF-8");
				model.setProFeature(proFeature);
			}
			if (StringUtils.isNotBlank(req.getProEnsureTxt())) {
				byte[] proEnsure = req.getProEnsureTxt().getBytes("UTF-8");
				model.setProEnsure(proEnsure);
			}
			if (StringUtils.isNotBlank(req.getCoverCaseTxt())) {
				byte[] coverCase = req.getCoverCaseTxt().getBytes("UTF-8");
				model.setCoverCase(coverCase);
			}
			if (StringUtils.isNotBlank(req.getCoverFlowTxt())) {
				byte[] coverFlow = req.getCoverFlowTxt().getBytes("UTF-8");
				model.setCoverFlow(coverFlow);
			}
			model.setCreateDate(new Timestamp(this.getCurrentTime()));
			//默认是“未上线”
			model.setProStatus(1);
			
			Long ret = overseaSafeInfoService.add(model);
			if (ret != null) {
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("添加成功");
			} else {
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("添加失败");
			}
			resp.setResult(model);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: updateOverseaSafeInfo
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/updateOverseaSafeInfo", method = RequestMethod.POST)
	public ResponseBase<OverseaSafeInfo> updateOverseaSafeInfo(
			@RequestBody OverseaSafeInfoReq req) {
		ResponseBase<OverseaSafeInfo> resp = new ResponseBase<OverseaSafeInfo>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			OverseaSafeInfo model = overseaSafeInfoService.findById(req.getId());
			ReqToModelHelper.copyReqValueToModel(req, model);
			if (StringUtils.isNotBlank(req.getProFeatureTxt())) {
				byte[] proFeature = req.getProFeatureTxt().getBytes("UTF-8");
				model.setProFeature(proFeature);
			}else{
				model.setProFeature(null);
			}
			if (StringUtils.isNotBlank(req.getProEnsureTxt())) {
				byte[] proEnsure = req.getProEnsureTxt().getBytes("UTF-8");
				model.setProEnsure(proEnsure);
			}else{
				model.setProEnsure(null);
			}
			if (StringUtils.isNotBlank(req.getCoverCaseTxt())) {
				byte[] coverCase = req.getCoverCaseTxt().getBytes("UTF-8");
				model.setCoverCase(coverCase);
			}else{
				model.setCoverCase(null);
			}
			if (StringUtils.isNotBlank(req.getCoverFlowTxt())) {
				byte[] coverFlow = req.getCoverFlowTxt().getBytes("UTF-8");
				model.setCoverFlow(coverFlow);
			}else{
				model.setCoverFlow(null);
			}
			overseaSafeInfoService.update(model);
			resp.setResult(model);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: deleteOverseaSafeInfo
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteOverseaSafeInfo", method = RequestMethod.POST)
	public ResponseBase<OverseaSafeInfo> deleteOverseaSafeInfo(
			@RequestBody OverseaSafeInfoReq req) {
		ResponseBase<OverseaSafeInfo> resp = new ResponseBase<OverseaSafeInfo>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			OverseaSafeInfo dp = new OverseaSafeInfo();
			dp.setId(req.getId());
			overseaSafeInfoService.delete(dp);

			resp.setResult(dp);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("删除成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}	
	
}